<template>
  <el-dialog
    :model-value="modelValue"
    width="600px"
    :before-close="handleClose"
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <template #header>
      <div class="flex border-b border-gray-200">
        <div
          :class="[
            'flex-1 py-4 px-5 text-center cursor-pointer font-medium transition-all border-b-2',
            dialogActiveTab === 'appointment'
              ? 'text-red-500 border-red-500 '
              : 'text-gray-600 border-transparent hover:text-red-500'
          ]"
          @click="dialogActiveTab = 'appointment'"
        >
          新增预约
        </div>
        <div
          :class="[
            'flex-1 py-4 px-5 text-center cursor-pointer font-medium transition-all border-b-2',
            dialogActiveTab === 'occupation'
              ? 'text-red-500 border-red-500 '
              : 'text-gray-600 border-transparent hover:text-red-500'
          ]"
          @click="dialogActiveTab = 'occupation'"
        >
          临时占用
        </div>
      </div>
    </template>
    <!-- 新增预约内容 -->
    <div v-show="dialogActiveTab === 'appointment'" class="p-5">
      <el-form
        ref="appointmentFormRef"
        :model="appointmentForm"
        :rules="formRules"
        class="max-h-96 overflow-y-auto"
      >
        <!-- 搜索会员 -->
        <el-form-item label="搜索会员" prop="search">
          <div class="flex flex-1 gap-3 w-full sm:w-auto">
            <el-input
              v-model="memberSearchKeyword"
              placeholder="会员姓名、手机号、卡号"
              class="flex-1"
            />
            <el-button type="warning" @click="searchMembers">搜索</el-button>
          </div>
        </el-form-item>
        <!-- 顾客信息 -->
        <el-form-item label="顾客姓名" prop="name" required>
          <el-input v-model="appointmentForm.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile" required>
          <el-input
            v-model="appointmentForm.mobile"
            placeholder="请输入11位真实手机号"
          />
        </el-form-item>

        <!-- 预约时间 -->
        <el-form-item label="预约日期" prop="date" required>
          <el-select
            v-model="selectedDate"
            placeholder="选择日期"
            @change="onDateSelectChange"
          >
            <el-option
              v-for="dateItem in availableDates"
              :key="dateItem.date"
              :label="`${dateItem.date} ${dateItem.dayOfWeekStr}`"
              :value="dateItem.date"
            />
          </el-select>
        </el-form-item>

        <!-- 预约内容 -->
        <div class="my-2 p-4 rounded-lg">
          <div class="mb-4">
            <span class="text-gray-700 font-medium">预约内容：</span>
          </div>

          <el-form-item label="服务项目" prop="pid">
            <el-select
              v-model="appointmentForm.pid"
              placeholder="选择服务项目"
              style="width: 100%"
            >
              <el-option
                v-for="project in availableProjects"
                :key="project.p_id"
                :label="`${project.p_name} (¥${project.p_price})`"
                :value="project.p_id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="预约员工" prop="tid">
            <el-select
              v-model="appointmentForm.tid"
              placeholder="选择技师"
              style="width: 100%"
            >
              <el-option
                v-for="employee in availableEmployees"
                :key="employee.t_id"
                :label="employee.t_name"
                :value="employee.t_id"
                :disabled="!employee.is_can"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="预约时间" prop="startTime" required>
            <div class="flex items-center gap-2 w-full">
              <el-select
                v-model="appointmentForm.startTime"
                placeholder="请选择时间"
                style="flex: 1"
                :disabled="!selectedDate"
                @change="onStartTimeChange"
              >
                <el-option
                  v-for="timeSlot in availableTimeSlots"
                  :key="timeSlot.startDate"
                  :label="formatTimeSlot(timeSlot.startDate)"
                  :value="timeSlot.startDate"
                  :disabled="!timeSlot.canMakeAppointment"
                />
              </el-select>
              <span class="text-gray-600 font-bold">-</span>
              <el-select
                v-model="appointmentForm.endTime"
                placeholder="自动计算"
                style="flex: 1"
                :disabled="!appointmentForm.startTime"
              >
                <el-option
                  v-for="timeSlot in endTimeOptions"
                  :key="timeSlot.value"
                  :label="timeSlot.label"
                  :value="timeSlot.value"
                />
              </el-select>
            </div>
          </el-form-item>

          <div class="flex gap-4">
            <el-button type="warning" text @click="addProject">
              <el-icon><Plus /></el-icon> 添加项目
            </el-button>
            <el-button type="primary" text @click="addService">
              <el-icon><Plus /></el-icon> 添加一项
            </el-button>
          </div>
        </div>

        <!-- 预约备注 -->
        <el-form-item label="预约备注">
          <el-input
            v-model="appointmentForm.remark"
            type="textarea"
            placeholder="备注不超过200个字"
            :maxlength="200"
            show-word-limit
            :rows="4"
          />
        </el-form-item>
      </el-form>
    </div>
    <!-- 临时占用内容 -->
    <div
      v-show="dialogActiveTab === 'occupation'"
      class="p-10 text-center text-gray-500"
    >
      <p>临时占用功能开发中...</p>
    </div>
    <template #footer>
      <div class="flex justify-end gap-3 pt-4">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="warning" :loading="loading" @click="submitAppointment">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import Plus from "~icons/ep/plus";

// 导入API服务
import {
  addAppointment,
  getAppointmentDates,
  getEmployeeList,
  getTimeSlots,
  getProjectList,
  type AppointmentForm as ApiAppointmentForm,
  type AppointmentDate,
  type Employee,
  type TimeSlot,
  type Project
} from "@/api/appointment";

// 基础类型定义
interface AppointmentForm {
  mid?: string;
  name: string;
  mobile: string;
  date: string;
  tid: string;
  pid: string;
  remark: string;
  startTime: string;
  endTime: string;
}

const props = defineProps<{
  modelValue: boolean;
}>();

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  refresh: [];
}>();

// 状态
const loading = ref(false);
const appointmentFormRef = ref();
const dialogActiveTab = ref("appointment");

// 会员搜索
const memberSearchKeyword = ref("");

// 预约表单数据
const appointmentForm = ref<AppointmentForm>({
  name: "",
  mobile: "",
  date: "",
  tid: "",
  pid: "",
  remark: "",
  startTime: "",
  endTime: ""
});

// 日期和时间相关
const selectedDate = ref("");
const availableDates = ref<AppointmentDate[]>([]);
const availableTimeSlots = ref<TimeSlot[]>([]);

// 可用员工
const availableEmployees = ref<Employee[]>([]);

// 可用项目
const availableProjects = ref<Project[]>([]);

// 表单验证规则
const formRules = {
  name: [{ required: true, message: "请输入顾客姓名", trigger: "blur" }],
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  date: [{ required: true, message: "请选择预约日期", trigger: "change" }],
  startTime: [{ required: true, message: "请选择预约时间", trigger: "change" }]
};

// 计算结束时间选项
const endTimeOptions = computed(() => {
  if (!appointmentForm.value.startTime) return [];
  const startTime = new Date(appointmentForm.value.startTime);
  const options = [];
  // 生成30分钟到4小时的时间选项
  for (let i = 30; i <= 240; i += 15) {
    const endTime = new Date(startTime.getTime() + i * 60000);
    const timeStr = endTime.toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: false
    });
    const fullDateTime = `${selectedDate.value} ${timeStr}:00`;
    options.push({
      label: timeStr,
      value: fullDateTime
    });
  }
  return options;
});

// 日期选择变化处理
async function onDateSelectChange(date: string) {
  if (!date) return;
  selectedDate.value = date;
  appointmentForm.value.date = date;
  // 清空时间选择
  appointmentForm.value.startTime = "";
  appointmentForm.value.endTime = "";

  try {
    // 加载对应日期的可用时间段
    const response = await getTimeSlots(date);
    if (response.code === 1) {
      availableTimeSlots.value = response.data;
    }

    // 加载对应日期的可用员工
    const employeeResponse = await getEmployeeList(date);
    if (employeeResponse.code === 1) {
      availableEmployees.value = employeeResponse.data;
    }
  } catch (error) {
    console.error("加载时间段或员工信息失败:", error);
    ElMessage.error("加载时间段信息失败");
  }
}

// 开始时间变化处理
function onStartTimeChange(startTime: string) {
  appointmentForm.value.startTime = startTime;
  appointmentForm.value.endTime = ""; // 清空结束时间
}

// 格式化时间段显示
function formatTimeSlot(dateTimeStr: string): string {
  const date = new Date(dateTimeStr);
  return date.toLocaleTimeString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
    hour12: false
  });
}

// 搜索会员
async function searchMembers() {
  if (!memberSearchKeyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  try {
    // 这里可以调用会员搜索API
    // 根据API文档，会员列表接口是 /admin/member.php?act=list
    console.log("搜索会员:", memberSearchKeyword.value);

    // 如果需要集成会员搜索，可以在这里添加API调用
    // const response = await getMemberList({ keys: memberSearchKeyword.value });

    ElMessage.info("会员搜索功能开发中...");
  } catch (error) {
    console.error("搜索会员失败:", error);
    ElMessage.error("搜索失败");
  }
}

// 添加项目
function addProject() {
  ElMessage.info("添加项目功能开发中...");
}

// 添加一项
function addService() {
  ElMessage.info("添加服务功能开发中...");
}

// 提交预约
async function submitAppointment() {
  // 使用 Element Plus 表单验证
  try {
    await appointmentFormRef.value?.validate();
  } catch (error) {
    return; // 验证失败，直接返回
  }

  try {
    loading.value = true;

    // 构造API请求数据
    const requestData: ApiAppointmentForm = {
      mid: appointmentForm.value.mid
        ? Number(appointmentForm.value.mid)
        : undefined,
      name: appointmentForm.value.name,
      mobile: appointmentForm.value.mobile,
      date: appointmentForm.value.startTime, // 使用开始时间作为预约时间
      tid: appointmentForm.value.tid,
      pid: appointmentForm.value.pid,
      remark: appointmentForm.value.remark
    };

    const response = await addAppointment(requestData);

    if (response.code === 1) {
      ElMessage.success("预约成功");
      emit("update:modelValue", false);
      resetForm();
      emit("refresh"); // 通知父组件刷新
    } else {
      ElMessage.error(response.msg || "预约失败");
    }
  } catch (error) {
    console.error("预约失败:", error);
    ElMessage.error("预约失败，请重试");
  } finally {
    loading.value = false;
  }
}

// 重置表单
function resetForm() {
  appointmentForm.value = {
    name: "",
    mobile: "",
    date: "",
    tid: "",
    pid: "",
    remark: "",
    startTime: "",
    endTime: ""
  };
  selectedDate.value = "";
  memberSearchKeyword.value = "";
  dialogActiveTab.value = "appointment";
  availableTimeSlots.value = [];

  // 清除表单验证状态
  appointmentFormRef.value?.clearValidate();
}

// 关闭对话框处理
function handleClose() {
  emit("update:modelValue", false);
  resetForm();
}

// 加载可用日期
async function loadAvailableDates() {
  try {
    const response = await getAppointmentDates();
    if (response.code === 1) {
      // 转换日期格式：从ISO格式转为YYYY-MM-DD格式
      availableDates.value = response.data.map(item => ({
        date: item.date.split("T")[0], // 提取日期部分
        dayOfWeekStr: item.dayOfWeekStr
      }));
    }
  } catch (error) {
    console.error("加载可用日期失败:", error);
    ElMessage.error("加载可用日期失败");
  }
}

// 加载项目列表
async function loadProjects() {
  try {
    const response = await getProjectList({ status: "1" }); // 只获取上架的项目
    if (response.code === 1) {
      availableProjects.value = response.data;
    }
  } catch (error) {
    console.error("加载项目列表失败:", error);
    ElMessage.error("加载项目列表失败");
  }
}

// 监听对话框打开状态，打开时加载数据
watch(
  () => props.modelValue,
  newValue => {
    if (newValue) {
      loadAvailableDates();
      loadProjects();
    }
  }
);

// 组件挂载时加载基础数据
onMounted(() => {
  loadAvailableDates();
  loadProjects();
});
</script>
